import 'package:flutter/material.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/provider/nav_key.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/widgets/dialog/dialog_utils.dart';
import '../provider/browser_proviser.dart';
import '../viewmodel/before_browser.dart';
import 'browser.dart';

class RootBrowserPage extends StatefulWidget {
  String url;
  Function? onClose;
  RootBrowserPage({super.key,required this.url, this.onClose});

  @override
  State<RootBrowserPage> createState() => _RootBrowserPageState();
}

class _RootBrowserPageState extends State<RootBrowserPage> {
  List<String> userScripts = [];

  String get url => widget.url;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    String webUrl = url;
    if (webUrl.startsWith('http') || webUrl.startsWith('https')) {
      widget.url = webUrl;
    } else {
      widget.url = 'https://' + webUrl;
    }
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      initPage();
    });
  }
  void goBrowser(){
    try{
      String token1 = '${NativeChannelBridge.instance.appCommMsg?.token}';
      String email = '${NativeChannelBridge.instance.appCommMsg?.email}';
      Future<String> tokenJs = Future.value(
          "window._kaipayToken='${token1}';window._kaipayEmail='${email}';");
      // Log.logger.e('${NativeChannelBridge.instance.appCommMsg?.token}---token');
      BuildContext context = NavKey.navKey.currentContext!;
      List<Future<String>>? jsScriptFuture = [];
      Wallet? wallet = NavKey.getContext().read<WalletInfoNotifier>().wallet;
      Future<String> postJs = Future.value(
          'window.Kai={postMessage:function(json){window.flutter_inappwebview.callHandler("postMessage",json)},ethTransactionResult:function(json){window.flutter_inappwebview.callHandler("ethTransactionResult",json)}}');
      // 注入evm
      kaiPrint('goBrowser wallet $wallet');
      if (wallet != null) {
        // Future<String> vConsoleJs =
        // DefaultAssetBundle.of(context).loadString('assets/js/vconsole.js');
        Future<String> trustJs = DefaultAssetBundle.of(context)
            .loadString('assets/chaincore/trust_min.js');
        Map<String, dynamic> map =
        NavKey.getContext().read<BrowserProvider>().getNetworkAndNode();
        Chain chain = map['chain'];
        NodeInfo node = map['node'];
        Future<String> initJs = Future.value(
            'var config={ethereum:{chainId: ${chain.evmInfo!.chainId},rpcUrl:"${node.url}"},solana:{cluster:"mainnet-beta"},isDebug:false};trustwallet.ethereum=new trustwallet.Provider(config);trustwallet.solana=new trustwallet.SolanaProvider(config);trustwallet.postMessage=(json)=>{window.flutter_inappwebview.callHandler("postMessage",JSON.stringify(json))};window.ethereum=trustwallet.ethereum;window.ethereum.isMetaMask=true;window.ethereum.isKai=true;');
        // vConsoleJs,
        jsScriptFuture = [ tokenJs ,trustJs, initJs, postJs];
      } else {
        jsScriptFuture = [ tokenJs, postJs];
      }

      // config
      //  'window.ethereum.selectedAddress="0xe2be444ef66780a7d5b5a81604229935b99823fa";'

// 注入tron
      // Future<String> tronWebJs =
      //     DefaultAssetBundle.of(context).loadString('assets/chaincore/tronweb.js');
      // Future<String> kaiWalletTronJs = Future.value(
      //     'window._kaiwallet={postMessage:function(j){window.flutter_inappwebview.callHandler("postMessage",j)}};');
// tron 回调处理
      // Future<String> tronPostMessageJs = DefaultAssetBundle.of(context)
      //     .loadString('assets/chaincore/inject_tron.js');
      Future.wait(jsScriptFuture).then((value) {
        userScripts = value;
        if(mounted)setState(() {});
      }).onError((error, stackTrace) {
        kaiPrint(error);
      });
    }catch(e){
      kaiPrint('go to brower  error ${e.toString()}');
    }
  }

  void initPage(){
    try{
      // 设置标签信息
      BeforeBrowserController().setSearchIn(true);
      var list = SP().getBrowserInsideValid();
      if (!list.contains(widget.url)) {
        DialogUtils.showBrowserInside(context: NavKey.getContext()!, url: widget.url, canCallBack:true).then((value){
          if(value=='Success'){
            goBrowser();
          }else if(value=='Failed'){
            if(widget.onClose!=null){
              widget.onClose!();
            }
          }
        });
        return;
      }
      goBrowser();
    }catch(e){
      kaiPrint('webUrl ${url} initPage ${e.toString()}');
    }
  }


  @override
  Widget build(BuildContext context) {
    if(userScripts.length == 0){
      return Container(
        color: Colors.transparent,
      );
    }
    return BrowserPage(
        url: url,
        userScripts: userScripts,
        onClose :widget.onClose
    );
  }
}
